package com.zxw.文件.PDF.util;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.IOException;

/**
 * @projectName: ruoyi
 * @package: com.ruoyi.common.utils.pdf
 * @className: WatermarkPageEvent
 * @author: zhangxuewei
 * @description: TODO
 * @date: 2023/9/22 10:14
 * @version: 1.0
 */
public class WatermarkPageEvent extends PdfPageEventHelper {


    private String info;

    private String fontAddr;


    public WatermarkPageEvent(String info, String fontAddr) {
        this.info = info;
        this.fontAddr = fontAddr;
    }

    public void onEndPage(PdfWriter writer, Document document) {
        BaseFont bf = null;
        try {
            bf = BaseFont.createFont(fontAddr, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Font font = new Font(bf, 10, Font.NORMAL, new BaseColor(128, 128, 128));
        // 获取页面大小
        Rectangle pageSize = document.getPageSize();

        // 创建水印文本
        PdfContentByte content = writer.getDirectContentUnder();
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(0.4f); // 设置透明度
        content.setGState(gs);


        float xInterval = 100; // 水印之间的水平间隔
        float yInterval = 100; // 水印之间的垂直间隔

        // Y坐标为0，沿X轴每间隔100生成水印信息
        for (float x = 0; x < pageSize.getWidth(); x = x + xInterval) {
            ColumnText.showTextAligned(content,
                    Element.ALIGN_CENTER, new Phrase(info, font),
                    x, 0, 45);
        }

        // X坐标为0，沿Y轴每间隔100生成水印信息
        for (float y = 100; y < pageSize.getHeight(); y = y + xInterval) {
            ColumnText.showTextAligned(content,
                    Element.ALIGN_CENTER, new Phrase(info, font),
                    0, y, 45);
        }

    }

}